package com.xiangxiao.rpan.settings.controller;

import cn.hutool.core.bean.BeanUtil;
import com.xiangxiao.rpan.settings.constant.GlobalConsts;
import com.xiangxiao.rpan.settings.constant.ResponseCode;
import com.xiangxiao.rpan.settings.constant.ResponseMessage;
import com.xiangxiao.rpan.settings.dto.InstallSystemDTO;
import com.xiangxiao.rpan.settings.dto.JsonObject;
import com.xiangxiao.rpan.settings.dto.SystemConfigDTO;
import com.xiangxiao.rpan.settings.exception.SettingsException;
import com.xiangxiao.rpan.settings.service.SystemConfigService;
import com.xiangxiao.rpan.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2023/6/17 11:03
 */
@Slf4j
@RestController
@RequestMapping("/api")
public class InstallController {
  private static Logger logger = LoggerFactory.getLogger(SiteController.class);
  @Autowired
  private SystemConfigService systemConfigService;

  @GetMapping("/install/status")
  public JsonObject isInstall() {
    try {
      boolean installed = systemConfigService.getSystemIsInstalled();
      if (BooleanUtils.isFalse(installed) || BooleanUtils.isTrue(installed)) {
        return new JsonObject(ResponseMessage.QUERY_INSTALLED_STATUS_SUECCESS, ResponseCode.OK, installed);
      } else {
        return new JsonObject(ResponseMessage.INSTALLED_STATUS_ISVALID, ResponseCode.FAIL);
      }
    } catch (Exception e) {
      logger.error(ResponseMessage.QUERY_INSTALLED_STATUS_FAILED, e);
      return new JsonObject(ResponseMessage.QUERY_INSTALLED_STATUS_FAILED, ResponseCode.QUERY_INSTALLED_STATUS_FAILED);
    }
  }

  @PostMapping("/install")
  public JsonObject install(@RequestBody InstallSystemDTO installSystemDTO) {
    if (systemConfigService.getSystemIsInstalled()) {
      throw new SettingsException("请勿重复初始化");
    };

    try {
      installSystemDTO.setPassword(MD5Util.encode(installSystemDTO.getPassword()));
      SystemConfigDTO systemConfigDTO = new SystemConfigDTO();
      BeanUtil.copyProperties(installSystemDTO, systemConfigDTO);
      systemConfigDTO.setInstalled(true);
      systemConfigService.updateSystemConfig(systemConfigDTO);

      return new JsonObject(ResponseMessage.INITIALIZATION_SUECCESS, ResponseCode.OK);
    } catch (Exception e) {
      logger.error(ResponseMessage.INITIALIZATION_FAILED, e);
      return new JsonObject(ResponseMessage.INITIALIZATION_FAILED, ResponseCode.INITIALIZATION_FAILED);
    }
  }

}
